__author__ = 'Administrator'

import sys
import xlrd


class SheetLoader:
    # Excel 表加载类，用于加载Excel表

    def __init__(self):
        # 构造函数
        self.file_path = ''
        self.sheet_name = ''

        self.workbook = None
        self.sheet = None

        self.num_rows = 0
        self.num_cols = 0

    def load(self, file_path, sheet_name):
        # 解析Excel表格，成功返回True，否则返回False

        self.file_path = file_path
        self.sheet_name = sheet_name

        # 打开Excel文件
        try:
            self.workbook = xlrd.open_workbook(self.file_path)
        except BaseException as e:
            print('Error: Load excel file failed', self.file_path)
            sys.exit(-1)

        # 打开Excel表格
        try:
            self.sheet = self.workbook.sheet_by_name(self.sheet_name)
        except BaseException as e:
            print('Load excel sheet failed', self.sheet_name)
            sys.exit(-1)

        # 行数和列数
        self.num_rows = len(self.sheet.col_values(0))
        self.num_cols = len(self.sheet.row_values(0))

        print('Load', self.file_path, self.sheet_name, self.num_rows, self.num_cols)

        return True

    # 得到表的名称
    def get_sheet_name(self):
        return self.sheet_name

    # 得到行数
    def get_num_rows(self):
        return self.num_rows

    # 得到列数
    def get_num_cols(self):
        return self.num_cols

    # 判断表中的数据是否为空
    def is_empty(self, row, col):
        return self.cell_value(row, col) == ''

    # 得到表格的内容
    def cell_value(self, row, col):
        return self.sheet.cell_value(row, col)

    # 得到Int值
    def get_int(self, row, col, def_value=0):
        cell_value = str(self.sheet.cell_value(row, col)).strip()
        if len(cell_value) == 0:
            return def_value

        return int(float(cell_value))

    # 得到bool值
    def get_bool(self, row, col, def_value=False):
        cell_value = str(self.sheet.cell_value(row, col)).strip()
        if len(cell_value) == 0:
            return def_value

        return int(cell_value) != 0

    # 得到Float值
    def get_float(self, row, col, def_value=0.0):
        cell_value = str(self.sheet.cell_value(row, col)).strip()
        if len(cell_value) == 0:
            return def_value

        return float(cell_value)

    # 得到String值（utf-8编码）
    def get_string(self, row, col, def_value=''):
        cell_value = self.sheet.cell_value(row, col)
        return str(cell_value).strip()
